import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:excel/excel.dart';
import 'package:intl/intl.dart';

class ExcelService {
  Future<String> exportAcceptanceFormsToExcel(List<Map<String, dynamic>> forms) async {
    // 创建Excel工作簿
    final excel = Excel.createExcel();
    final sheet = excel['受理单列表'];

    // 添加表头
    final headers = [
      '编号', '日期', '申请人姓名', '申请人联系方式', '申请人身份证号',
      '被申请人姓名', '被申请人联系方式', '被申请人身份证号', '纠纷描述',
      '受理人', '受理人单位', '受理人电话', '状态'
    ];

    for (var i = 0; i < headers.length; i++) {
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: i, rowIndex: 0)).value = TextCellValue(headers[i]);
    }

    // 添加数据行
    for (var i = 0; i < forms.length; i++) {
      final form = forms[i];
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 0, rowIndex: i + 1)).value = TextCellValue(form['formNumber']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 1, rowIndex: i + 1)).value = TextCellValue(form['date']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 2, rowIndex: i + 1)).value = TextCellValue(form['applicantInfo']['name']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 3, rowIndex: i + 1)).value = TextCellValue(form['applicantInfo']['contact']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 4, rowIndex: i + 1)).value = TextCellValue(form['applicantInfo']['idNumber']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 5, rowIndex: i + 1)).value = TextCellValue(form['respondentInfo']['name']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 6, rowIndex: i + 1)).value = TextCellValue(form['respondentInfo']['contact']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 7, rowIndex: i + 1)).value = TextCellValue(form['respondentInfo']['idNumber']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 8, rowIndex: i + 1)).value = TextCellValue(form['disputeDescription']);
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 9, rowIndex: i + 1)).value = TextCellValue(form['acceptorName'] ?? '');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 10, rowIndex: i + 1)).value = TextCellValue(form['acceptorUnit'] ?? '');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 11, rowIndex: i + 1)).value = TextCellValue(form['acceptorPhone'] ?? '');
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: 12, rowIndex: i + 1)).value = TextCellValue(form['status'] ?? '未处理');
    }

    // 保存文件
    final Directory tempDir = await getTemporaryDirectory();
    final String fileName = '受理单列表_${DateFormat('yyyyMMdd_HHmmss').format(DateTime.now())}.xlsx';
    final String filePath = '${tempDir.path}/$fileName';
    
    final file = File(filePath);
    await file.writeAsBytes(excel.encode()!);
    
    return filePath;
  }
} 